package com.scap.authen.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.scap.authen.dao.RoleAppDao;
import com.scap.authen.entity.RoleApp;
import com.scap.authen.entity.UserMapping;
import com.scap.authen.util.JDate;

@Service ("roleAppService")
@Transactional
public class RoleAppServiceImpl implements RoleAppService{
	@Autowired
	private ApplicationContext voContext;
	@Autowired
	private RoleAppDao voRoleAppDao;
	
	@Override
	public String saveRoleApp(String vaRoleId, String vaSiteId, String[] voApplicationId, HttpServletRequest request) {
		String vaResult = "";
		Locale voLocale = RequestContextUtils.getLocale(request);
		for ( int i = 0; i < voApplicationId.length; i++) {
			RoleApp voRoleApp = new RoleApp();
			voRoleApp.setVaApplicationId( voApplicationId[i]);
			voRoleApp.setVaRoleId(vaRoleId);
			voRoleApp.setVaSiteId(vaSiteId);
			voRoleApp.setVnInsertUserId(1);
			voRoleApp.setVaInsertDate(JDate.getDate());
			voRoleApp.setVaInsertTime(JDate.getTime());
			if ( voRoleAppDao.insertRoleApp((voRoleApp))){
				vaResult = voContext.getMessage("alert.save.success", null, voLocale);
			} else {
				vaResult = voContext.getMessage("alert.save.fail", null, voLocale);
			}
		}		
		return vaResult;
	}
	
	@Override
	public void deleteRoleAppByRoleIdSiteId(String vaRoleId, String vaSiteId) {
		voRoleAppDao.deleteRoleAppByRoleIdSiteId(vaRoleId, vaSiteId);		
	}
	
	@Override
	public String findApplicationChecked(String roleId, String siteId ) {
		String voAppChecked = "";
		List<RoleApp> voAppCheckedtList = voRoleAppDao.findApplicationChecked(roleId, siteId);
		if (voAppCheckedtList.size() != 1) {
			for(RoleApp voTempAppChecked: voAppCheckedtList){
				voAppChecked += voTempAppChecked.getVaApplicationId()+",";
			}
		} else {
			voAppChecked = voAppCheckedtList.get(0).getVaApplicationId();		
		}			
		return voAppChecked;
	}

	@Override
	public List<HashMap<String, String>> findApplicationByRoleIdSiteId(String roleId, String siteId) {
		List<Object[]> voAppList = voRoleAppDao.findApplicationByRoleIdSiteId(roleId, siteId);	
		List<HashMap<String, String>> voAppListMap = new ArrayList<HashMap<String,String>>();	
		for(Object[] voObject : voAppList){
			HashMap<String, String> voHash = new HashMap<String , String>();

			voHash.put("vaApplicationId", String.valueOf(voObject[0]));
			voHash.put("vaApplicationName", String.valueOf(voObject[1]));
			voAppListMap.add(voHash);
		}		
		return voAppListMap;
	}
}
